import { getData, setData } from '@/lib/storage';

const AUTH_LOCAL_STORAGE_KEY = `${import.meta.env.VITE_APP_NAME}-auth-v${
  import.meta.env.VITE_APP_VERSION || '1.0'
}`;

/**
 * Get stored auth information from local storage
 */
const getAuth = () => {
  try {
    const auth = getData(AUTH_LOCAL_STORAGE_KEY);
    if (!auth) return undefined;

    if (typeof import.meta !== 'undefined' && import.meta.env?.DEV) {
      // eslint-disable-next-line no-console
      console.log('[Auth] getAuth retrieved:', auth);
    }

    const accessToken = auth.accessToken || auth.access_token;
    const refreshToken = auth.refreshToken || auth.refresh_token;
    const expiresAt = auth.expiresAt || auth.expires_at || null;
    const expiresIn = auth.expiresIn || auth.expires_in || null;
    const tokenType = auth.tokenType || auth.token_type || 'Bearer';

    return {
      accessToken: accessToken ?? undefined,
      refreshToken: refreshToken ?? undefined,
      expiresAt: expiresAt ?? undefined,
      expiresIn: expiresIn ?? undefined,
      tokenType,
      user: auth.user || null,
    };
  } catch (error) {
    console.error('AUTH LOCAL STORAGE PARSE ERROR', error);
  }
};

/**
 * Save auth information to local storage
 */
const setAuth = (auth) => {
  if (!auth) {
    removeAuth();
    return;
  }

  if (typeof import.meta !== 'undefined' && import.meta.env?.DEV) {
    // eslint-disable-next-line no-console
    console.log('[Auth] setAuth storing:', auth);
  }

  const normalized = {
    accessToken: auth.accessToken || auth.access_token || null,
    refreshToken: auth.refreshToken || auth.refresh_token || null,
    expiresAt: auth.expiresAt || auth.expires_at || null,
    expiresIn: auth.expiresIn || auth.expires_in || null,
    tokenType: auth.tokenType || auth.token_type || 'Bearer',
    user: auth.user || null,
  };

  setData(AUTH_LOCAL_STORAGE_KEY, normalized);
};

/**
 * Remove auth information from local storage
 */
const removeAuth = () => {
  if (!localStorage) {
    return;
  }

  try {
    localStorage.removeItem(AUTH_LOCAL_STORAGE_KEY);
  } catch (error) {
    console.error('AUTH LOCAL STORAGE REMOVE ERROR', error);
  }
};

export { AUTH_LOCAL_STORAGE_KEY, getAuth, removeAuth, setAuth };
